<template>
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>

			<uni-forms ref="baseForm" :modelValue="meetingRoomApplyForm" :border="true" labelWidth="100px"
				label-position="left">

				<uni-forms-item label="申请部门" required >
					<!-- <picker type="default" :range="departNames" @change="departChange">
						<view class="picker-bg">{{departNameStr()}}</view>
					</picker> -->
					<view class="text-bg">{{ userInfo.departmentName }}</view>
				</uni-forms-item>
				
				<uni-forms-item label="申请人">
					<view class="text-bg">{{userName}}</view>
				</uni-forms-item>
				<uni-forms-item label="开始时间" required>
					<uni-datetime-picker type="datetime" return-type="timestamp"
						v-model="meetingRoomApplyForm.startTime" />
				</uni-forms-item>
				<uni-forms-item label="结束时间" required>
					<uni-datetime-picker type="datetime" return-type="timestamp"
						v-model="meetingRoomApplyForm.endTime" />
				</uni-forms-item>
				<uni-forms-item label="会议主题" required>
					<uni-easyinput type="text" v-model="meetingRoomApplyForm.topic" />
				</uni-forms-item>

				<uni-forms-item label="会议室" required >
					<picker type="default" :range="rooms" @change="roomChange">
						<view class="picker-bg">{{roomNameStr()}}</view>
					</picker>
				</uni-forms-item>

				<!-- 选择多人模板 -->
				<uni-forms-item label="参会人员" required>
					<uni-row v-if="meetingRoomApplyForm.attenders.length !=0">
						<uni-col :span="8" v-for="(item, idx) in meetingRoomApplyForm.attenders" :key="idx">
							<view class="user-bg">
									<text>{{item.name}}</text>
							</view>
						</uni-col>
					</uni-row>
					<button @click="clickSelectAttender" class="btn-add">添加参会人员</button>
				</uni-forms-item>

				<uni-forms-item label="使用人数" required>
					<uni-easyinput type="number" v-model="meetingRoomApplyForm.renshu" @change="renshuChange" />
				</uni-forms-item>

				<uni-forms-item label="设备(多选)" ></uni-forms-item>
					<checkbox-group @change="equipChange">
							<uni-row>
								<uni-col :span="8" v-for="(sb,idx) in shebeilist" :key="idx">
									<view class="check-css"  >
										<checkbox :value="sb">{{sb}}</checkbox>
									</view>
								</uni-col>
							</uni-row>
					</checkbox-group>

				<uni-forms-item label="接待品(多选)" ></uni-forms-item>
				<checkbox-group @change="itemChange">
						<uni-row>
							<uni-col :span="8" v-for="(jd,idx) in jiedaipinlist" :key="idx">
								<view class="check-css"  >
									<checkbox :value="jd">{{jd}}</checkbox>
								</view>
							</uni-col>
						</uni-row>
				</checkbox-group>

				<uni-forms-item label="备注">
					<uni-easyinput type="textarea" v-model="meetingRoomApplyForm.remark" @change="chuanci2" @input="chuanci2"  autoHeight />
				</uni-forms-item>


				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in meetingRoomApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.topic}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>开始时间：{{getFormatedTimeStr(item.startTime)}}</view>
						<view>结束时间：{{getFormatedTimeStr(item.endTime)}}</view>
						<view>会议室：{{item.room}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>
			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>
	</view>
</template>

<script>
	import {
		websock
	} from '../../net/websock'
	import moment from 'moment'
import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				currentIndex: 0,
				items: ['会议室申请', '申请记录'],
				rooms: [],
				departNames: [],
				departIds: [],
				departIndex: 0,
				shebeilist:['投影仪','电视','其他'],
				jiedaipinlist:['席卡','其他'],
				userName: '',
				moreStatus: 'more',
				applyRecord: [],
				userInfo: {},
				meetingRoomApplyForm: {
					startTime: 0,
					endTime: 0,
					topic: '',
					renshu: '',
					roomIdx: 0,
					remark: '',
					equips: [],
					items: [],
					attenders: [],
					auditors: []
				}
			}
		},
		async onReady() {
			console.log('zhuanzheng shenqing on ready')

			try {
				this.userInfo = await websock.getUserInfo()
				this.userName = this.userInfo.name

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					this.departNames.push(departList[i].name)
					this.departIds.push(departList[i].id)
				}
				console.log('depart list', departList)

				let rooms = await websock.huiyishiList()
				for (let i = 0; i != rooms.length; i++) {
					this.rooms.push(rooms[i].name)
				}

				let auditors = await websock.getAuditors({typ: 7})
				quchongAuditors(auditors)
				this.meetingRoomApplyForm.auditors = auditors.slice()

				this.getNewestRecord()
			} catch (e) {
				uni.showToast({
					title: e.message
				})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 获取最新的通知
			async getNewestRecord() {
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.meetingRoomApplyRecord({
							pageCount: 10
						})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.meetingRoomApplyRecord({
							greaterThan: this.applyRecord[0].id,
							pageCount: 10
						})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try {
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.meetingRoomApplyRecord({
							pageCount: 10
						})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.meetingRoomApplyRecord({
							lessThan: this.applyRecord[this.applyRecord.length - 1].id,
							pageCount: 10
						})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			roomChange(e) {
				console.log('room change', e.detail.value)
				this.meetingRoomApplyForm.roomIdx = e.detail.value
			},
			roomNameStr() {
				return this.rooms[this.meetingRoomApplyForm.roomIdx] || ''
			},
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},
			equipChange(e) {
				console.log('equip change', e)
				this.meetingRoomApplyForm.equips = e.detail.value
			},
			itemChange(e) {
				console.log('item change', e)
				this.meetingRoomApplyForm.items = e.detail.value
			},
			rmAuditor(idx) {
				this.meetingRoomApplyForm.auditors.splice(idx, 1)
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			clickSelectAttender() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.meetingRoomApplyForm.attenders || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.meetingRoomApplyForm.attenders = data.contactList
						}
					}
				})
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.meetingRoomApplyForm.auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.meetingRoomApplyForm.auditors = data.contactList
						}
					}
				})
			},
			async clickApply() {
				console.log('click apply')

				if (!this.meetingRoomApplyForm.startTime) return uni.showToast({
					title: '请选择开始时间'
				})
				if (!this.meetingRoomApplyForm.endTime) return uni.showToast({
					title: '请选择结束时间'
				})
				if (!this.meetingRoomApplyForm.topic) return uni.showToast({
					title: '请输入会议主题'
				})

				if (this.meetingRoomApplyForm.attenders.length == 0) return uni.showToast({title: '请选择参会人'})

				if (!this.meetingRoomApplyForm.renshu) return uni.showToast({title: '请选择使用人数'})

				let auditors = []
				for (let i = 0; i != this.meetingRoomApplyForm.auditors.length; i++) {
					auditors.push({uid: this.meetingRoomApplyForm.auditors[i].uid, stepName: this.meetingRoomApplyForm.auditors[i].stepName || this.meetingRoomApplyForm.auditors[i].positionName})
				}

				try {
					await websock.meetingRoomApply({
						department: this.userInfo.departmentName,
						startTime: this.meetingRoomApplyForm.startTime,
						endTime: this.meetingRoomApplyForm.endTime,
						topic: this.meetingRoomApplyForm.topic,
						room: this.rooms[this.meetingRoomApplyForm.roomIdx],
						equips: this.meetingRoomApplyForm.equips,
						items: this.meetingRoomApplyForm.items,
						remark: this.meetingRoomApplyForm.remark,
						attenders: this.meetingRoomApplyForm.attenders,
						renshu: parseInt(this.meetingRoomApplyForm.renshu) || 0,
						auditors
					})

					uni.showToast({ title: '申请成功' })

					this.meetingRoomApplyForm = {
						startTime: 0,
						endTime: 0,
						topic: '',
						renshu: '',
						roomIdx: 0,
						remark: '',
						equips: [],
						items: [],
						attenders: []
					}

					this.currentIndex = 1
					this.getNewestRecord()
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
			},
			renshuChange() {
				this.meetingRoomApplyForm.renshu = parseInt(this.meetingRoomApplyForm.renshu) + ''
			},
			async revertApply(idx) {
				try {
					await websock.revertMeetingRoomApply({
						id: this.applyRecord[idx].id
					})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({
						title: err.message || 'error'
					})
				}
			},
			seeDetail(idx) {
				uni.navigateTo({
					url: `/pages/task/meetingroomApplyDetail?id=${this.applyRecord[idx].id}`
				})
			}
		}
	}
</script>

<style>
	@import '../common/common.css';
</style>
